import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useChatStore = defineStore('chat', () => {
  // 状态
  const connected = ref(false);
  const currentUser = ref({
    id: '',
    name: '',
    role: '' // 'doctor' 或 'user'
  });
  const sessions = ref([]);
  const activeSessionId = ref(null);
  const messages = ref({});
  const availableDoctors = ref([]);
  const availableUsers = ref([]);
  const inputMessage = ref('');
  const socket = ref(null);
  const connecting = ref(false);

  // 计算属性
  const activeSession = computed(() => {
    return sessions.value.find(s => s.sessionId === activeSessionId.value) || null;
  });

  const activeMessages = computed(() => {
    return messages.value[activeSessionId.value] || [];
  });

  // 方法
  function connect(role, userId, userName) {
    if (socket.value) {
      socket.value.close();
    }

    connecting.value = true;
    currentUser.value = { id: userId, name: userName, role };
    
    // 连接WebSocket
    const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${wsProtocol}//localhost:8082/websocket/${role}/${userId}`;
    console.log("---wsUrl--",wsUrl)
    socket.value = new WebSocket(wsUrl);

    socket.value.onopen = () => {
      connected.value = true;
      connecting.value = false;
      console.log('WebSocket连接成功');
    };

    socket.value.onmessage = (event) => {
      const message = JSON.parse(event.data);
      handleMessage(message);
    };

    socket.value.onerror = (error) => {
  console.error('WebSocket错误详情:', error); // 打印完整错误对象
  console.error('错误代码:', error.code || '未知');
  console.error('错误信息:', error.message || '无');
  
  connected.value = false;
  connecting.value = false;
  
  // 显示用户友好错误
  ElMessage.error(`连接错误: ${error.message || '无法建立连接'}`);
};

    socket.value.onclose = (event) => {
  console.log('WebSocket连接关闭事件:', event);
  console.log('关闭代码:', event.code);
  console.log('关闭原因:', event.reason);
  
  connected.value = false;
  connecting.value = false;
  
  // 根据关闭代码判断是否需要重连
  const shouldReconnect = [1006, 1011, 1012, 1013, 1014].includes(event.code);
  
  if (shouldReconnect) {
    console.log('尝试重新连接...');
    setTimeout(() => connect(currentUser.value.role, currentUser.value.id, currentUser.value.name), 3000);
  } else {
    console.log('无需重连，连接已正常关闭');
  }
};
  }

  function disconnect() {
    if (socket.value) {
      socket.value.close();
      socket.value = null;
    }
    connected.value = false;
    sessions.value = [];
    messages.value = {};
    activeSessionId.value = null;
  }

function createSession(targetId) {
  if (!connected.value) {
    console.error('未连接，无法创建会话');
    return;
  }
  
  // 关键修复：检查是否已有相同目标的会话
  const existingSession = sessions.value.find(session => {
    // 根据当前角色判断会话唯一性（医生-用户唯一对应）
    if (currentUser.value.role === 'doctor') {
      // 医生视角：查找相同userId的会话
      return session.userId === targetId;
    } else {
      // 用户视角：查找相同doctorId的会话
      return session.doctorId === targetId;
    }
  });
  
  if (existingSession) {
    // 如果已有会话，直接切换到该会话，不创建新会话
    console.log('已存在该用户会话，切换到现有会话');
    activeSessionId.value = existingSession.sessionId;
    return; // 跳出方法，不执行后续创建逻辑
  }
  
  // 以下为原创建会话逻辑（若不存在会话则继续）
  const message = {
    type: 'session',
    content: 'create',
    receiverId: targetId,
    timestamp: Date.now()
  };
  
  console.log('发送会话创建消息:', message);
  socket.value.send(JSON.stringify(message));
}
  function closeSession(sessionId) {
    if (!connected.value) return;

    const message = {
      type: 'session',
      content: 'close',
      sessionId,
      timestamp: Date.now()
    };

    socket.value.send(JSON.stringify(message));
    
    // 从本地状态移除会话
    sessions.value = sessions.value.filter(s => s.sessionId !== sessionId);
    if (activeSessionId.value === sessionId) {
      activeSessionId.value = sessions.value.length > 0 ? sessions.value[0].sessionId : null;
    }
  }

  function sendMessage(sessionId, content) {
    if (!connected.value || !content.trim()) return;

    const message = {
      type: 'chat',
      sessionId,
      senderId: currentUser.value.id,
      senderName: currentUser.value.name,
      content: content.trim(),
      timestamp: Date.now()
    };

    socket.value.send(JSON.stringify(message));
    
    // 本地添加消息
    if (!messages.value[sessionId]) {
      messages.value[sessionId] = [];
    }
    messages.value[sessionId].push({
      ...message,
      isSelf: true
    });
    
    inputMessage.value = '';
  }

  function switchSession(sessionId) {
    activeSessionId.value = sessionId;
  }

  function handleMessage(message) {
    switch (message.type) {
      case 'chat':
        handleChatMessage(message);
        break;
      case 'session':
        handleSessionMessage(message);
        break;
      case 'doctorList':
        availableDoctors.value = message.data || [];
        break;
      case 'userList':
        availableUsers.value = message.data || [];
        break;
      case 'system':
        showSystemMessage(message.content);
        break;
    }
  }

  function handleChatMessage(message) {
    if (!messages.value[message.sessionId]) {
      messages.value[message.sessionId] = [];
    }
    
    messages.value[message.sessionId].push({
      ...message,
      isSelf: message.senderId === currentUser.value.id
    });
    
    // 如果是当前活跃会话，滚动到底部
    if (activeSessionId.value === message.sessionId) {
      scrollToBottom();
    } else {
      // 否则更新未读计数
      const sessionIndex = sessions.value.findIndex(s => s.sessionId === message.sessionId);
      if (sessionIndex !== -1) {
        sessions.value[sessionIndex].unreadCount = (sessions.value[sessionIndex].unreadCount || 0) + 1;
      }
    }
  }

  function handleSessionMessage(message) {
  console.log('收到会话消息:', message);
  
  if (message.content === 'created') {
    const sessionInfo = message.data[0];
    
    // 关键修复：检查会话是否已存在（避免后端重复返回时添加）
    const sessionExists = sessions.value.some(s => s.sessionId === sessionInfo.sessionId);
    if (sessionExists) {
      console.log('会话已存在，不重复添加:', sessionInfo.sessionId);
      activeSessionId.value = sessionInfo.sessionId; // 仍切换到该会话
      return;
    }
    
    // 正常添加新会话（仅在不存在时）
    sessions.value.push({
      sessionId: sessionInfo.sessionId,
      doctorId: sessionInfo.doctorId,
      doctorName: sessionInfo.doctorName,
      userId: sessionInfo.userId,
      userName: sessionInfo.userName,
      unreadCount: 0,
      createTime: sessionInfo.createTime
    });
    
    activeSessionId.value = sessionInfo.sessionId;
  } else if (message.content === 'closed') {
      // 会话关闭
      sessions.value = sessions.value.filter(s => s.sessionId !== message.sessionId);
      if (activeSessionId.value === message.sessionId) {
        activeSessionId.value = sessions.value.length > 0 ? sessions.value[0].sessionId : null;
      }
  }
}

  function showSystemMessage(content) {
    // 系统消息处理
    if (activeSessionId.value) {
      messages.value[activeSessionId.value].push({
        type: 'system',
        content,
        timestamp: Date.now()
      });
      scrollToBottom();
    } else {
      // 如果没有活跃会话，创建一个临时系统消息会话
      if (!messages.value.system) {
        messages.value.system = [];
      }
      messages.value.system.push({
        type: 'system',
        content,
        timestamp: Date.now()
      });
    }
  }

  function scrollToBottom() {
    // 在实际组件中实现滚动到底部逻辑
    // 这里需要通过ref获取消息容器元素
  }

  function formatTime(timestamp) {
    const date = new Date(timestamp);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }

  return {
    connected,
    currentUser,
    sessions,
    activeSessionId,
    messages,
    availableDoctors,
    availableUsers,
    inputMessage,
    connecting,
    activeSession,
    activeMessages,
    connect,
    disconnect,
    createSession,
    closeSession,
    sendMessage,
    switchSession,
    formatTime
  };
});